package com.cn.parks.dao.impl;

import com.cn.parks.dao.TempParkingDao;
import com.cn.parks.entity.TempParking;
import com.cn.parks.utils.DBUtil;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.Instant;

/**
 * 临时停车记录数据访问实现类
 * 实现对临时停车记录表的增删改查等基本操作
 */
public class TempParkingDaoImpl implements TempParkingDao {
    
    /**
     * 添加临时停车记录
     * @param tempParking 临时停车记录对象
     * @return 影响的行数，1表示添加成功，0表示添加失败
     * @throws Exception SQL执行异常
     */
    @Override
    public int insert(TempParking tempParking) throws Exception {
        String sql = "INSERT INTO temp_parking (user_id, car_num) VALUES (?, ?)";
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, tempParking.getUserId());
            pstmt.setString(2, tempParking.getCarNum());
//            pstmt.setDate(3, new java.sql.Date(tempParking.getEntryDate().getTime()));
//            pstmt.setTime(4, new java.sql.Time(tempParking.getEntryTime().getTime()));
//            pstmt.setDate(5, tempParking.getOutDate() != null ? new java.sql.Date(tempParking.getOutDate().getTime()) : null);
//            pstmt.setTime(6, tempParking.getOutTime() != null ? new java.sql.Time(tempParking.getOutTime().getTime()) : null);
//            pstmt.setFloat(7, tempParking.getTempMoney() != null ? tempParking.getTempMoney() : 0.0f);
            return pstmt.executeUpdate();
        } finally {
            if (pstmt != null) pstmt.close();
            if (conn != null) DBUtil.closeConnection(conn);
        }
    }

    /**
     * 根据ID删除临时停车记录
     * @param tempId 临时停车记录ID
     * @return 影响的行数，1表示删除成功，0表示删除失败
     * @throws Exception SQL执行异常
     */
    @Override
    public int deleteById(String tempId) throws Exception {
        String sql = "DELETE FROM temp_parking WHERE temp_id = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, tempId);
            return pstmt.executeUpdate();
        } finally {
            if (pstmt != null) pstmt.close();
            if (conn != null) DBUtil.closeConnection(conn);
        }
    }

    /**
     * 更新临时停车记录
     * @param carNum 临时停车记录对象
     * @return 影响的行数，1表示更新成功，0表示更新失败
     * @throws Exception SQL执行异常
     */
    @Override
    public int update(Float tempMoney, String duration , String carNum) throws Exception {
        String sql = "UPDATE temp_parking SET out_date = CURRENT_TIMESTAMP ,temp_money = ? ,duration = ? WHERE car_num = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
//        Date outDate;
        try {
//            // 获取当前时间并设置时区为东八区（北京时间）
//            ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
//            Instant instant = zonedDateTime.toInstant();
//            outDate = Date.from(instant);
//
//            // 打印调试信息
//            System.out.println("Current time in Asia/Shanghai: " + zonedDateTime);
//            System.out.println("Converted to Date: " + outDate);

            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
//            pstmt.setTimestamp(1, new java.sql.Timestamp(outDate.getTime()));
            pstmt.setFloat(  1, tempMoney);
            pstmt.setString(  2, duration);
            pstmt.setString(3, carNum);
            return pstmt.executeUpdate();
        } finally {
            if (pstmt != null) pstmt.close();
            if (conn != null) DBUtil.closeConnection(conn);
        }
    }

    /**
     * 根据ID查询临时停车记录
     * @param tempId 临时停车记录ID
     * @return 临时停车记录对象，如果不存在返回null
     * @throws Exception SQL执行异常
     */
    @Override
    public TempParking getById(String tempId) throws Exception {
        String sql = "SELECT * FROM temp_parking WHERE temp_id = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, tempId);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                return extractTempParkingFromResultSet(rs);
            }
            return null;
        } finally {
            if (rs != null) rs.close();
            if (pstmt != null) pstmt.close();
            if (conn != null) DBUtil.closeConnection(conn);
        }
    }

    /**
     * 查询所有临时停车记录
     * @return 临时停车记录列表
     * @throws Exception SQL执行异常
     */
    @Override
    public List<TempParking> getAll() throws Exception {
        String sql = "SELECT * FROM temp_parking";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<TempParking> list = new ArrayList<>();
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()) {

                list.add(extractTempParkingFromResultSet(rs));
            }
            return list;
        } finally {
            if (rs != null) rs.close();
            if (pstmt != null) pstmt.close();
            if (conn != null) DBUtil.closeConnection(conn);
        }
    }

    /**
     * 根据车牌号查询临时停车记录
     * @param carNum 车牌号
     * @return 临时停车记录列表
     * @throws Exception SQL执行异常
     */
    @Override
    public List<TempParking> getByCarNum(String carNum) throws Exception {
        String sql = "SELECT * FROM temp_parking WHERE car_num = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<TempParking> list = new ArrayList<>();
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, carNum);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                list.add(extractTempParkingFromResultSet(rs));
            }
            return list;
        } finally {
            if (rs != null) rs.close();
            if (pstmt != null) pstmt.close();
            if (conn != null) DBUtil.closeConnection(conn);
        }
    }

    /**
     * 根据日期范围查询临时停车记录
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return 临时停车记录列表
     * @throws Exception SQL执行异常
     */
    @Override
    public List<TempParking> getByDateRange(Date startDate, Date endDate) throws Exception {
        String sql = "SELECT * FROM temp_parking WHERE entry_date BETWEEN ? AND ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<TempParking> list = new ArrayList<>();
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setDate(1, new java.sql.Date(startDate.getTime()));
            pstmt.setDate(2, new java.sql.Date(endDate.getTime()));
            rs = pstmt.executeQuery();
            while (rs.next()) {
                list.add(extractTempParkingFromResultSet(rs));
            }
            return list;
        } finally {
            if (rs != null) rs.close();
            if (pstmt != null) pstmt.close();
            if (conn != null) DBUtil.closeConnection(conn);
        }
    }

    /**
     * 根据卡ID查询临时停车记录
     * @param cardId 卡ID
     * @return 临时停车记录列表
     * @throws Exception SQL执行异常
     */
    @Override
    public List<TempParking> getByCardId(String cardId) throws Exception {
        String sql = "SELECT * FROM temp_parking WHERE card_id = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<TempParking> list = new ArrayList<>();
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, cardId);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                list.add(extractTempParkingFromResultSet(rs));
            }
            return list;
        } finally {
            if (rs != null) rs.close();
            if (pstmt != null) pstmt.close();
            if (conn != null) DBUtil.closeConnection(conn);
        }
    }

    /**
     * 查询未离场的车辆记录
     * @return 未离场的临时停车记录列表
     * @throws Exception SQL执行异常
     */
    @Override
    public List<TempParking> getNotOutCars() throws Exception {
        String sql = "SELECT * FROM temp_parking WHERE out_date IS NULL";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<TempParking> list = new ArrayList<>();
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()) {
                list.add(extractTempParkingFromResultSet(rs));
            }
            return list;
        } finally {
            if (rs != null) rs.close();
            if (pstmt != null) pstmt.close();
            if (conn != null) DBUtil.closeConnection(conn);
        }
    }

    @Override
   public int getTodayIn() throws Exception {
       String sql = "SELECT COUNT(*) FROM temp_parking WHERE DATE(entry_date) = CURDATE()";
       Connection conn = null;
       PreparedStatement pstmt = null;
       ResultSet rs = null;
       int count = 0;
       try {
           conn = DBUtil.getConnection();
           pstmt = conn.prepareStatement(sql);
           rs = pstmt.executeQuery();
           if (rs.next()) {
               count = rs.getInt(1);
           }
           return count;
       } finally {
           if (rs != null) rs.close();
           if (pstmt != null) pstmt.close();
           if (conn != null) DBUtil.closeConnection(conn);
       }
   }

   @Override
   public int getTodayOut() throws Exception {
       String sql = "SELECT COUNT(*) FROM temp_parking WHERE DATE(out_date) = CURDATE()";
       Connection conn = null;
       PreparedStatement pstmt = null;
       ResultSet rs = null;
       int count = 0;
       try {
           conn = DBUtil.getConnection();
           pstmt = conn.prepareStatement(sql);
           rs = pstmt.executeQuery();
           if (rs.next()) {
               count = rs.getInt(1);
           }
           return count;
       } finally {
           if (rs != null) rs.close();
           if (pstmt != null) pstmt.close();
           if (conn != null) DBUtil.closeConnection(conn);
       }
   }

   @Override
   public Float getTodayIncome() throws Exception {
       String sql = "SELECT SUM(temp_money) FROM temp_parking WHERE DATE(out_date) = CURDATE()";
       Connection conn = null;
       PreparedStatement pstmt = null;
       ResultSet rs = null;
       float totalIncome = 0;
       try {
           conn = DBUtil.getConnection();
           pstmt = conn.prepareStatement(sql);
           rs = pstmt.executeQuery();
           if (rs.next()) {
               totalIncome = rs.getFloat(1);
           }
           return totalIncome;
       } finally {
           if (rs != null) rs.close();
           if (pstmt != null) pstmt.close();
           if (conn != null) DBUtil.closeConnection(conn);
       }
   }

   /**
    * 根据车牌号查询入场时间
    * @param carNum 车牌号
    * @return 入场时间
    * @throws Exception SQL执行异常
    */
   @Override
   public Timestamp getEntryTimeByCarNum(String carNum) throws Exception {
       String sql = "SELECT entry_date FROM temp_parking WHERE car_num = ?";
       Connection conn = null;
       PreparedStatement pstmt = null;
       ResultSet rs = null;
       Timestamp entryDate = null;
       try {
           conn = DBUtil.getConnection();
           pstmt = conn.prepareStatement(sql);
           pstmt.setString(1, carNum);
           rs = pstmt.executeQuery();
           if (rs.next()) {
               System.out.println("entry_date------->"+ rs.getTimestamp("entry_date"));
               entryDate = rs.getTimestamp("entry_date");
               System.out.println("entry_date------->"+ entryDate);
               System.out.println("entry_dateTime------->"+ entryDate.getTime());
           }
           return entryDate;
       } finally {
           if (rs != null) rs.close();
           if (pstmt != null) pstmt.close();
           if (conn != null) DBUtil.closeConnection(conn);
       }
   }

   /**
    * 根据车牌号查询入场时间
    * @param carNum 车牌号
    * @return 入场时间
    * @throws Exception SQL执行异常
    */
    @Override
    public Time getEntryTimeByCarNum2(String carNum) throws Exception {
        String sql = "SELECT entry_date FROM temp_parking WHERE car_num = ?";
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        Time entryTime = null;
        try {
            conn = DBUtil.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, carNum);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                entryTime = rs.getTime("entry_date");
            }
            return entryTime;
        } finally {
            if (rs != null) rs.close();
            if (pstmt != null) pstmt.close();
            if (conn != null) DBUtil.closeConnection(conn);
        }
        }


    /**
     * 从ResultSet中提取TempParking对象的辅助方法
     * @param rs ResultSet结果集
     * @return TempParking对象
     * @throws Exception SQL执行异常
     */
    private TempParking extractTempParkingFromResultSet(ResultSet rs) throws Exception {
        TempParking tempParking = new TempParking();
        tempParking.setTempId(rs.getInt("temp_id"));
        tempParking.setUserId(rs.getInt("user_id"));
        tempParking.setCarNum(rs.getString("car_num"));
        tempParking.setEntryDate(rs.getDate("entry_date"));
        tempParking.setEntryTime(rs.getTime("entry_date"));
//        System.out.println("entry_time:"+tempParking.getEntryTime());
        tempParking.setOutDate(rs.getDate("out_date"));
        tempParking.setOutTime(rs.getTime("out_date"));
        tempParking.setTempMoney(rs.getFloat("temp_money"));
        tempParking.setDuration(rs.getString("duration"));
        return tempParking;
    }
        public String getDuration(Date entryDate,Date outDate) {
        if (outDate != null && entryDate != null) {
            System.out.println("outDate: " + outDate);
            System.out.println("entryDate: " + entryDate);
            long durationInMillis = (outDate.getTime() - entryDate.getTime()) / 60000;
            System.out.println("durationInMillis: " + durationInMillis); // 添加调试信息
            String hours = String.valueOf(durationInMillis / 60); // 计算小时
            String minutes = String.valueOf(durationInMillis % 60); // 计算剩余分钟
            return hours + " 小时 " + minutes + " 分钟"; // 返回停车时长
        }
        return "未出场"; // 如果没有出场时间
    }
} 